package com.example.thirdstage_project.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.thirdstage_project.ov.LoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.example.thirdstage_project.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * @author 86158
 * @version 1.0
 * Create by 2022/12/7 21:52
 */
@Slf4j
@Service
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       /* //获取session
        HttpSession session = request.getSession();
        //获取session中的用户
        Object user = session.getAttribute("user");
        //判断用户是否存在
        if (user == null) {
            //不存在，拦截
            response.setStatus(401);
            return false;
        }
        //存在，保存到TreadLocal
        UserHolder.saveUser((UserDTO) user);*/

        //TODO Redis
        //1.获取请求头中的token
        String authorization = request.getHeader("authorization");
        if (StrUtil.isBlank(authorization)) {
            response.setStatus(401);
            return false;
        }
        //2.基于token获取redis中的用户
        Map<Object, Object> user = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + authorization);
        //3.判断
        if (user.isEmpty()) {
            //不存在，拦截
            response.setStatus(401);
            return false;
        }
        //转为user对象
        LoginVO loginVO = BeanUtil.fillBeanWithMap(user, new LoginVO(), false);
        //存在，保存到TreadLocal
        UserHolder.saveUser(loginVO);
        //刷新token的有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + authorization,RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
